<template>
  <div class="form-edit-container">
    <div class="left-board">
      <el-tabs v-model="currentTab" class="center-tabs">
        <el-tab-pane label="组件列表" name="componnents" />
        <el-tab-pane label="表单设置" name="form" />
      </el-tabs>
      <el-scrollbar v-show="currentTab === 'componnents'" class="left-scrollbar">
        <div class="components-list">
          <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
            <div class="components-title">
              {{ item.title }}
            </div>
            <draggable :clone="cloneComponent" :group="{ name: 'componentsGroup', pull: 'clone', put: false }" :list="item.list" :sort="false" class="components-draggable" draggable=".components-item" @end="onEnd">
              <div v-for="(element, index) in item.list" :key="index" class="components-item" @click="addComponent(element)" >
                <div class="components-body">
                  {{ element.__config__.label }}
                </div>
              </div>
            </draggable>
          </div>
        </div>
      </el-scrollbar>
      <el-scrollbar v-show="currentTab === 'form'" class="left-scrollbar">
        <el-form label-width="100px" size="small">
          <el-form-item label="表单类型:">
            <el-select v-model="formConf.formType"  size="mini" style="max-width: 150px;">
              <el-option label="申请类" :value="0" />
              <el-option label="预约登记" :value="1" />
              <el-option label="活动报名" :value="2" />
              <el-option label="问卷调查" :value="3" />
              <el-option label="意见反馈" :value="4" />
              <el-option label="投票类" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="显示标题:">
            <el-switch v-model="formConf.showTitle" size="mini"/>
          </el-form-item>
          <el-form-item label="显示描述:">
            <el-switch v-model="formConf.showDescribe" size="mini"/>
          </el-form-item>
          <el-form-item label="显示序号:">
            <el-switch v-model="formConf.showNumber" size="mini" />
          </el-form-item>
          <el-form-item label="标签对齐:">
            <el-radio-group v-model="formConf.labelPosition" size="mini">
              <el-radio-button label="left">左边</el-radio-button>
              <el-radio-button label="right">右边</el-radio-button>
              <el-radio-button label="top">顶部</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标签宽度:">
            <el-input-number v-model.number="formConf.labelWidth" :min="100" placeholder="请输入标签宽度" size="mini" style="max-width: 200px;"/>
          </el-form-item>
          <el-form-item label="栅格间隔:">
            <el-input-number v-model="formConf.gutter" :min="0" placeholder="栅格间隔" style="max-width: 200px;"/>
          </el-form-item>
          <el-form-item label="表单尺寸:">
            <el-radio-group v-model="formConf.size" size="mini">
              <el-radio-button label="medium"> 中等 </el-radio-button>
              <el-radio-button label="small"> 较小 </el-radio-button>
              <el-radio-button label="mini"> 迷你 </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="可编辑:">
            <el-switch v-model="formConf.disabled" size="mini"/>
          </el-form-item>
          <el-form-item label="表单背景:">
            <el-row>
              <el-row align="middle" type="flex">
                <el-col :spvan="18">
                  <el-radio-group v-model="formConf.backgroundType" size="mini" @change="selectBackgroundType">
                    <el-radio-button label="color">颜色</el-radio-button>
                    <el-radio-button label="img">图片</el-radio-button>
                  </el-radio-group>
                </el-col>
              </el-row>
            </el-row>
            <el-row v-if="formConf.backgroundType=='color'">
              <el-row align="middle" type="flex">
                <el-col :spvan="18">
                  <el-color-picker v-model="formConf.backgroundColor" size="mini" />
                </el-col>
              </el-row>
            </el-row>
            <el-row v-if="formConf.backgroundType=='img'">
              <el-row align="middle" type="flex">
                <el-col :spvan="18">
                  <el-button size="small" type="text" @click="openBackImgDialog">上传背景</el-button>
                </el-col>
              </el-row>
            </el-row>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <div class="center-board">
      <el-scrollbar class="center-scrollbar" :style="{
        backgroundColor: formConf.backgroundType ==='color' ? formConf.backgroundColor : '',
        backgroundImage: formConf.backgroundType ==='img' ? 'url('+formConf.backgroundImg+')' : '',
        backgroundSize: 'cover',
        }">
        <el-row v-if="formConf" :gutter="formConf.gutter" class="center-board-row">
          <el-row v-if="formConf.showTitle" align="middle" justify="center" type="flex" class="center-board-row-header">
            <el-col class="form-head-title">
              <h4 class="form-name-text" contenteditable="true" @blur="(event)=>{ this.formConf.title=event.target.innerText; this.saveProjectInfo()}">
                {{ formConf.title }}
              </h4>
            </el-col>
          </el-row>
          <el-row v-if="formConf.showDescribe" align="middle" justify="center" type="flex" class="center-board-row-header">
            <el-col class="form-head-desc">
              <Tinymce :height="200" v-if="editDescription" v-model="formConf.description"  @blur="editDescription=false" @input="saveProjectInfo()" />
              <div v-else class="form-name-text" @click="editDescription=true" v-html="formConf.description" />
            </el-col>
          </el-row>
          <el-form :disabled="formConf.disabled" :label-position="formConf.labelPosition" :label-width="formConf.labelWidth + 'px'" :size="formConf.size">
            <draggable :animation="340" :list="drawingList" class="drawing-board" group="componentsGroup" @end="onItemEnd">
              <draggable-item
                v-for="(item, index) in drawingList"
                :key="item.renderKey"
                :active-id="activeId"
                :current-item="item"
                :drawing-list="drawingList"
                :form-conf="formConf"
                :index="index"
                @activeItem="activeFormItem"
                @changeLabel="changeLabel"
                @copyItem="drawingItemCopy"
                @deleteItem="drawingItemDelete"
              />
            </draggable>
            <div v-show="!drawingList.length" class="empty-info">
              <img style="width: 20%" src="@/assets/images/form-bg.png">
              <p>从左侧拖入或点选组件进行表单设计</p>
            </div>
          </el-form>
        </el-row>
      </el-scrollbar>
    </div>
    <ImgSelect ref="backImg" :max="1" :choose-list="backImgbArr" @getUrl="getBackImgUrl" />
    <right-panel v-if="activeData" :active-data="activeData" :form-conf="formConf" :show-form="true" :show-field="!!drawingList.length" @tag-change="tagChange" @data-change="updateProjectItemInfo" />
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { debounce } from 'throttle-debounce'
import RightPanel from './RightPanel'
import Tinymce from '@/components/Tinymce'
import ImgSelect from '@/components/goodsMaterial/img'
import {
  assistComponents,
  formConf,
  imageComponents,
  inputComponents,
  personalInfoComponents,
  selectComponents
} from '@/components/generator/config'
import { deepClone } from '@/utils'
import { dbDataConvertForItemJson, formItemConvertData } from '@/utils/convert'
import drawingDefalut from '@/components/generator/drawingDefalut'
import DraggableItem from './DraggableItem'
import { saveDrawingList, saveIdGlobal } from '@/utils/db'
import { projectUpdate,projectList,formKey,maxFormId,itemUpdate,itemDelete,itemCreate,itemSort } from '@/api/form'

let oldActiveId
let tempActiveData
let idGlobal

export default {
  components: {
    draggable,
    RightPanel,
    DraggableItem,
    Tinymce,
    ImgSelect
  },
  data() {
    return {
      idGlobal,
      formConf: null,
      showForm: true,
      currentTab: 'componnents',
      backImgbArr: [],
      editDescription: true,
      inputComponents,
      selectComponents,
      labelWidth: 100,
      drawingList: drawingDefalut,
      drawingData: {},
      activeId: drawingDefalut.length != 0 ? drawingDefalut[0].formId : 0,
      formData: {},
      dialogVisible: false,
      generateConf: null,
      showFileName: false,
      activeData: drawingDefalut ? drawingDefalut[0] : null,
      saveDrawingListDebounce: debounce(340, saveDrawingList),
      saveIdGlobalDebounce: debounce(340, saveIdGlobal),
      formKey: null,
      leftComponents: [
        {
          title: '联系人组件',
          list: personalInfoComponents
        },
        {
          title: '输入型组件',
          list: inputComponents
        },
        {
          title: '图片型组件',
          list: imageComponents
        },
        {
          title: '辅助型组件',
          list: assistComponents
        },
        {
          title: '选择型组件',
          list: selectComponents
        }
      ]
    }
  },
  computed: {},
  watch: {
    'activeData.__config__.label': function(val, oldVal) {
      if (this.activeData.placeholder === undefined || !this.activeData.__config__.tag || oldActiveId !== this.activeId) {
        return
      }
      this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val
    },
    activeId: {
      handler(val) {
        oldActiveId = val
      },
      immediate: true
    },
    drawingList: {
      handler(val) {
        this.saveDrawingListDebounce(val, this.formKey)
        if (val.length === 0) this.idGlobal = 100
      },
      deep: true
    },
    idGlobal: {
      handler(val) {
        if (val) {
          this.saveIdGlobalDebounce(val, this.formKey)
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 复制对象 避免修改改变原始对象
    this.formConf = JSON.parse(JSON.stringify(formConf))
    // 项目key
    this.formKey = this.$route.query.key
    // 从服务端获取
    this.queryProjectItems()
    // 获取表单配置
    formKey(this.formKey).then(res =>{
      if(res){
        if(res.code){
          this.$message.error(`${res.msg}`);
        }else{
          this.formConf.title = res.name
          this.formConf.description = res.describe
        }
      }
    })
    // 全局组件Id
    maxFormId(this.formKey).then(res =>{
      if(res){
        if(res.code){
          this.$message.error(`${res.msg}`);
        }else{
          this.idGlobal = res ? res : 100
        }
      }
    })
  },
  methods: {
    changeTinymce(el) {
      console.log(el)
    },
    selectBackgroundType(e) {
    },
    openBackImgDialog() {
      this.backImgbArr = this.formConf.backgroundImg === '' ? [] : [this.formConf.backgroundImg]
      this.$refs.backImg.dialog = true
    },
    getBackImgUrl(arr) {
      this.formConf.backgroundImg = arr[0]
      this.$refs.backImg.clearValidate('formConf.backgroundImg')
    },
    saveProjectInfo: debounce(430, true, function() {
      projectUpdate({
        'key': this.formKey,
        'type': this.formConf.formType,
        'name': this.formConf.title,
        'describe': this.formConf.description,
        'formConfig': this.formConf
      }).then(res =>{
        if(res){
          if(res.code){
            this.$message.error(`${res.msg}`);
          }else{
          }
        }
      })
    }),
    updateProjectItemInfo(val) {
      const data = formItemConvertData(val, this.formKey)
      itemUpdate(data).then(() =>{

      })
    },
    deleteProjectItemInfo(val) {
      const data = formItemConvertData(val, this.formKey)
      itemDelete(data).then(()=>{})
    },
    async saveProjectItemInfo(item) {
      let isSuccess = false
      const params = formItemConvertData(item, this.formKey)
      const pItem = item

      itemCreate(params).then(res =>{
        if(res){
          if(res.code){
            this.$message.error(`${res.msg}`);
          }else{
            pItem.sort = res.sort
            isSuccess = true
          }
        }
      })
      // 如果是分页组件 刷新所有分页的页码
      if (item.typeId === 'PAGINATION') {
        this.updatePaginationList()
      }
      return isSuccess
    },
    updatePaginationList() {
      // 页总数
      const length = this.drawingList.filter(item => item.typeId === 'PAGINATION').length
      let curr = 1
      this.drawingList.forEach((item, index) => {
        if (item.typeId === 'PAGINATION') {
          item.totalPageNum = length
          item.currPageNum = curr++
          this.$set(this.drawingList, index, item)
        }
      })
    },
    queryProjectItems() {
      projectList(this.formKey).then(res =>{
        if(res){
          if(res.code){
            this.$message.error(`${res.msg}`);
          }else{
            this.drawingList = res.map(item => dbDataConvertForItemJson(item))
            this.updatePaginationList()
          }
        }
      })
    },
    activeFormItem(currentItem) {
      this.activeData = currentItem
      this.activeId = currentItem.__config__.formId
    },
    changeLabel(currentItem, value) {
      console.log(currentItem)
      console.log(value)
    },
    onEnd(obj) {
      if (obj.from !== obj.to) {
        this.activeData = tempActiveData
        this.activeId = this.idGlobal
        this.saveProjectItemInfo(tempActiveData).then(() => {
          this.onItemEnd(obj)
        })
      }
    },
    onItemEnd(obj) {

      const params = { 'formKey': this.formKey }
      if (this.drawingList[obj.newIndex - 1]) {
        const sort1 = this.drawingList[obj.newIndex - 1].sort
        params.beforePosition = sort1
      }
      if (this.drawingList[obj.newIndex + 1]) {
        const sort2 = this.drawingList[obj.newIndex + 1].sort
        params.afterPosition = sort2
      }
      params.formItemId = this.drawingList[obj.newIndex].__config__.formId
      if (params.beforePosition || params.afterPosition) {
        itemSort(params).then(res =>{
          this.drawingList[obj.newIndex].sort = res.sort
        })
      }
    },
    addComponent(item) {
      const clone = this.cloneComponent(item)
      this.saveProjectItemInfo(clone)
      this.drawingList.push(clone)
      this.activeFormItem(clone)
    },
    cloneComponent(origin) {
      const clone = deepClone(origin)
      const config = clone.__config__
      config.span = this.formConf.span // 生成代码时，会根据span做精简判断
      this.createIdAndKey(clone)
      clone.placeholder !== undefined && (clone.placeholder += config.label)
      tempActiveData = clone
      return tempActiveData
    },
    createIdAndKey(item) {
      const config = item.__config__
      config.formId = ++this.idGlobal
      config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
      if (config.layout === 'colFormItem') {
        item.__vModel__ = `field${this.idGlobal}`
      } else if (config.layout === 'rowFormItem') {
        config.componentName = `row${this.idGlobal}`
        !Array.isArray(config.children) && (config.children = [])
        delete config.label // rowFormItem无需配置label属性
      }
      if (Array.isArray(config.children)) {
        config.children = config.children.map(childItem => this.createIdAndKey(childItem))
      }
      //alert(JSON.stringify(config))
      return item
    },
    empty() {
      this.$confirm('确定要清空所有组件吗？', '提示', { type: 'warning' })
        .then(
          () => {
            this.drawingList = []
            this.idGlobal = 100
          }
        )
    },
    drawingItemCopy(item, list) {
      let clone = deepClone(item)
      clone = this.createIdAndKey(clone)
      list.push(clone)
      this.activeFormItem(clone)
      this.saveProjectItemInfo(clone)
    },
    drawingItemDelete(index, list) {
      const item = list[index]
      list.splice(index, 1)
      this.$nextTick(() => {
        const len = this.drawingList.length
        if (len) {
          this.activeFormItem(this.drawingList[len - 1])
        }
      })
      this.deleteProjectItemInfo(item)
    },
    tagChange(newTag) {
      newTag = this.cloneComponent(newTag)
      const config = newTag.__config__
      newTag.__vModel__ = this.activeData.__vModel__
      newTag.sort = this.activeData.sort
      config.formId = this.activeId
      config.span = this.activeData.__config__.span
      this.activeData.__config__.tag = config.tag
      this.activeData.__config__.tagIcon = config.tagIcon
      this.activeData.__config__.document = config.document
      this.activeData.typeId = newTag.typeId
      if (typeof this.activeData.__config__.defaultValue === typeof config.defaultValue) {
        config.defaultValue = this.activeData.__config__.defaultValue
      }
      Object.keys(newTag)
        .forEach(key => {
          if (this.activeData[key] !== undefined) {
            newTag[key] = this.activeData[key]
          }
        })
      this.activeData = newTag
      this.updateProjectItemInfo(newTag)
      this.updateDrawingList(newTag, this.drawingList)
    },
    updateDrawingList(newTag, list) {
      const index = list.findIndex(item => item.__config__.formId === this.activeId)
      if (index > -1) {
        list.splice(index, 1, newTag)
      } else {
        list.forEach(item => {
          if (Array.isArray(item.__config__.children)) this.updateDrawingList(newTag, item.__config__.children)
        })
      }
    }
  }
}
</script>

<style lang='scss'>
@import '@/assets/styles/form/home';
@import '@/assets/styles/form/index';
</style>
<style lang="scss" scoped>
.center-board {
  .center-board-row {
    margin-right: 10px;
  }
  .center-board-row-header {
    margin-bottom: 10px;
  }
  .form-head-title {
    padding: 0 10px;
    text-align: center;
    .form-name-text:hover{
      border: 1px dashed #7b7b7b;
    }
  }
  .form-head-desc {
    padding: 0 10px;
  }
  .form-head-divider {
    margin-right: 10px;
    margin-left: 10px;
    width: auto;
  }
}

</style>
